package org.fuxia.im.listeners;

import javax.swing.SwingUtilities;

import org.fuxia.im.common.ClientContext;
import org.fuxia.im.common.CommonDialog;
import org.fuxia.im.common.MyMessageDialog;
import org.fuxia.im.common.MyMessageDialog.MessageDialogClickHandler;
import org.fuxia.im.core.ECMessageType;
import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.listeners.Listener;
import org.fuxia.im.entities.User;
import org.fuxia.im.gui.Chat;


/**
 * 文件传输的响应处理类
 *
 */
public class FileTransferListener implements Listener {

	public void trigger(Object param) {
		ECPacket packet = (ECPacket) param;
		switch (ECMessageType.valueOf(packet.getMessageType())) {
		case FILE_TRANSFER_INFO:
			handlerFileTransferInfo(packet);
			break;
		case FILE_TRANSFER_ACK:
			handlerFileTransferAck(packet);
			break;
		case CANCEL_FILE_TRANSFER:
			handlerCancel(packet);
			break;
		default:
			break;
		}
	}

	/**
	 * 处理文件传送确认信息
	 * @param packet
	 */
	private void handlerFileTransferAck(final ECPacket packet) {
		SwingUtilities.invokeLater(new Runnable() {
			
			public void run() {
				Chat chatWindow = ClientContext.getValue(packet.getFrom(), Chat.class);
				if (chatWindow != null) {
					chatWindow.startFileTransfer(packet.getParameter("ip"),
							packet.getParameter("port"));
				}
			}
		});
	}

	/**
	 * 处理文件传输请求响应信息
	 * @param packet
	 */
	private void handlerFileTransferInfo(final ECPacket packet) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				Chat chatWindow = ClientContext.getValue(packet.getFrom(), Chat.class);
				final String fileName = packet.getParameter("fileName");
				final String fileSize = packet.getParameter("fileSize");
				final String fileSuffix = packet.getParameter("fileType");
				if (chatWindow != null) {
					
					chatWindow.addFileReceivePanel(fileName, fileSize, fileSuffix);
					chatWindow.repaint();
				}else {
					String message = String.format("【%s】向你发送文件，文件名：%s,文件大小：%s字节", packet.getFrom(),fileName,fileSize) ;
					MyMessageDialog md = CommonDialog.createMessageNotifyWindow(message) ;
					md.setClickHandler(new MessageDialogClickHandler() {
						public void doAction() {
							User user = ClientContext.findUserByCode(packet.getFrom()) ;
							Chat cw = new Chat(user);
							ClientContext.putValue(packet.getFrom(), cw);
							cw.addFileReceivePanel(fileName, fileSize, fileSuffix);
							cw.setVisible(true);
						}
					});
					md.showDialog();
				}
			}
		});
	}

	private void handlerCancel(final ECPacket packet) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				Chat chatWindow = ClientContext.getValue(packet.getFrom(), Chat.class);
				if (chatWindow != null) {
					chatWindow.closeFileSendPane();
					chatWindow.insertErrorMessage(packet.getParameter("info"));
				}
				
			}
		});
	}
}
